<template>
  <div class="task-manager">
    <page-header
      title="任务管理"
      description="管理和监控自动化任务的执行状态，支持查看任务详情、执行记录等。"
    >
      <el-input v-model="searchQuery" placeholder="搜索任务..." class="search-input" clearable>
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </page-header>

    <div class="content-wrapper">
      <div class="task-grid" v-loading="loading">
        <div v-for="task in filteredTasks" :key="task.id" class="task-card">
          <div class="card-header" :class="task.mediaType">
            <div class="task-info">
              <div class="task-name" :title="task.name">{{ task.name }}</div>
              <div class="task-id">{{ task.workOrderId }}</div>
            </div>
            <div class="task-status" :class="task.status.toLowerCase()">
              <el-icon v-if="task.status === '成功'"><CircleCheckFilled /></el-icon>
              <el-icon v-else-if="task.status === '运行中'"><Loading /></el-icon>
              <el-icon v-else><CircleCloseFilled /></el-icon>
              {{ task.status }}
            </div>
          </div>

          <div class="card-body">
            <div class="description">{{ task.description }}</div>
            <div class="host-info">
              <div class="info-item">
                <el-icon><Monitor /></el-icon>
                <span>执行主机：</span>
                <el-tooltip
                  v-if="getHostList(task.execHost).length > 0"
                  placement="top"
                  :content="task.execHost"
                  :show-after="200"
                >
                  <div class="host-tags">
                    <el-tag
                      v-for="(host, index) in getHostList(task.execHost).slice(0, 3)"
                      :key="host"
                      size="small"
                      type="info"
                      class="host-tag"
                    >
                      {{ host }}
                    </el-tag>
                    <span v-if="getHostList(task.execHost).length > 3" class="more-hosts">
                      +{{ getHostList(task.execHost).length - 3 }}
                    </span>
                  </div>
                </el-tooltip>
              </div>
            </div>

            <div class="execution-info">
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ task.execType }}</span>
              </div>
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span>{{ task.execUser }}</span>
              </div>
            </div>

            <div class="workflow-steps">
              <div class="step-title">
                <el-icon><Connection /></el-icon>
                <span>执行步骤</span>
                <el-tooltip
                  v-if="task.mediaType === '工作流' && task.skipped?.length"
                  placement="top"
                  :show-after="200"
                  :enterable="true"
                >
                  <template #content>
                    <div class="skipped-info">
                      <div class="info-header">
                        <el-icon><Warning /></el-icon>
                        <span>已跳过以下脚本执行</span>
                      </div>
                      <div class="info-content">
                        <div v-for="script in task.skipped" :key="script" class="skipped-item">
                          <el-icon><DocumentDelete /></el-icon>
                          <span>{{ script }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-tag size="small" type="warning" effect="light" class="skipped-count">
                    已跳过 {{ task.skipped.length }} 个脚本
                  </el-tag>
                </el-tooltip>
              </div>
              <el-steps :active="getActiveStep(task)" simple>
                <el-step
                  v-for="(resource, index) in task.resources"
                  :key="index"
                  :status="getStepStatus(resource.status)"
                  class="step-item"
                >
                  <template #title>
                    <div class="step-content">
                      <el-tooltip
                        placement="top"
                        :show-after="200"
                        :hide-after="200"
                        :enterable="true"
                      >
                        <template #content>
                          <div class="pod-info">
                            <div class="info-item">
                              <span class="label">Pod名称</span>
                              <span class="value">{{ resource.pod_name }}</span>
                            </div>
                            <div class="info-item">
                              <span class="label">工作流</span>
                              <span class="value">{{ resource.workflow }}</span>
                            </div>
                            <div class="info-item">
                              <span class="label">状态</span>
                              <span class="value" :class="resource.status.toLowerCase()">
                                {{ resource.status }}
                              </span>
                            </div>
                            <div class="info-item">
                              <span class="label">UID</span>
                              <span class="value">{{ resource.uid }}</span>
                            </div>
                          </div>
                        </template>
                        <span class="step-name">{{ resource.step }}</span>
                      </el-tooltip>
                      <span class="step-status" :class="getStepStatus(resource.status)">
                        {{ resource.status }}
                      </span>
                    </div>
                  </template>
                </el-step>
              </el-steps>
            </div>
          </div>

          <div class="card-footer">
            <div class="time-info">
              <el-icon><Calendar /></el-icon>
              <span>创建于 {{ formatTime(task.createTime) }}</span>
            </div>
            <div class="actions">
              <el-button link type="primary" @click="handleViewDetail(task)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button link type="danger" @click="handleDelete(task)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="pagination">
        <TablePagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          :teleported="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <floating-action-button tooltip="创建新任务" @click="router.push('/task/create')" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  CircleCheckFilled,
  CircleCloseFilled,
  Loading,
  Clock,
  Monitor,
  User,
  Calendar,
  Connection,
  View,
  Delete,
  Warning,
  DocumentDelete,
} from '@element-plus/icons-vue'
import PageHeader from '@/components/common/PageHeader.vue'
import { formatDateTime } from '@/utils/date'
import { taskService } from '@/api/taskService'
import type { Task } from '@/api/taskService'
import TablePagination from '../../components/common/TablePagination.vue'
import FloatingActionButton from '@/components/common/FloatingActionButton.vue'

const loading = ref(false)
const tasks = ref<Task[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const showAllHosts = ref(false)
const router = useRouter()

// 将逗号分隔的主机字符串转换为数组
const getHostList = (hostStr: string): string[] => {
  return hostStr ? hostStr.split(',').map((host) => host.trim()) : []
}

// 过滤后的任务列表
const filteredTasks = computed(() => {
  if (!searchQuery.value) return tasks.value
  const query = searchQuery.value.toLowerCase()
  return tasks.value.filter(
    (task) =>
      task.name.toLowerCase().includes(query) ||
      task.workOrderId.toLowerCase().includes(query) ||
      task.description.toLowerCase().includes(query),
  )
})

// 获取步骤状态
const getStepStatus = (status: string) => {
  switch (status.toLowerCase()) {
    case '成功':
      return 'success'
    case 'pending':
    case '运行中':
      return 'process'
    case '失败':
      return 'error'
    default:
      return 'wait'
  }
}

// 获取当前活动步骤
const getActiveStep = (task: Task) => {
  const finishedSteps = task.resources.filter((r) => r.status === '成功').length
  return finishedSteps
}

// 格式化时间
const formatTime = (time: string) => {
  return formatDateTime(time)
}

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    const response = await taskService.getTasks({
      page: currentPage.value,
      page_size: pageSize.value,
    })
    if (response.items && Array.isArray(response.items)) {
      tasks.value = response.items
      total.value = response.total
    } else {
      console.error('Unexpected response format:', response)
      ElMessage.error('获取任务列表失败：数据格式错误')
    }
  } catch (err) {
    console.error('获取任务列表失败:', err)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查看详情
const handleViewDetail = (task: Task) => {
  // TODO: 实现查看详情的逻辑
  ElMessage.info('查看详情功能开发中...')
}

// 处理删除任务
const handleDelete = async (task: Task) => {
  try {
    await ElMessageBox.confirm(`确认删除任务 "${task.name}"？删除后将无法恢复。`, '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      closeOnClickModal: false,
      confirmButtonClass: 'el-button--danger',
    })

    loading.value = true
    await taskService.deleteTask(task.id)
    ElMessage.success('删除成功')
    fetchTasks()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除任务失败:', err)
      ElMessage.error('删除任务失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTasks()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchTasks()
}

// 初始化时获取数据
onMounted(() => {
  fetchTasks()
})
</script>

<style scoped lang="scss">
.task-manager {
  height: 100%;

  .content-wrapper {
    background: #fff;
    border-radius: 4px;
    min-height: calc(100% - 100px);
    position: relative;
    padding: 24px 24px 56px;

    .task-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 24px;
      margin-bottom: 24px;

      .task-card {
        background: #fff;
        border-radius: 8px;
        border: 1px solid var(--el-border-color-lighter);
        transition: all 0.3s;
        overflow: hidden;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          transform: translateY(-2px);
        }

        .card-header {
          padding: 16px;
          border-bottom: 1px solid var(--el-border-color-lighter);
          display: flex;
          justify-content: space-between;
          align-items: center;
          position: relative;
          overflow: hidden;

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            opacity: 0.1;
            z-index: 0;
          }

          &.工作流 {
            &::before {
              background-color: var(--el-color-primary);
            }

            .task-info {
              .task-name::before {
                content: '⚡';
                margin-right: 6px;
              }
            }
          }

          &.脚本 {
            &::before {
              background-color: var(--el-color-success);
            }

            .task-info {
              .task-name::before {
                content: '📜';
                margin-right: 6px;
              }
            }
          }

          .task-info {
            position: relative;
            z-index: 1;

            .task-name {
              font-size: 16px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
              display: flex;
              align-items: center;
            }

            .task-id {
              font-size: 13px;
              color: var(--el-text-color-secondary);
            }
          }

          .task-status {
            position: relative;
            z-index: 1;
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 13px;

            &.成功 {
              background-color: var(--el-color-success-light-9);
              color: var(--el-color-success);
            }

            &.运行中 {
              background-color: var(--el-color-primary-light-9);
              color: var(--el-color-primary);
            }

            &.失败 {
              background-color: var(--el-color-danger-light-9);
              color: var(--el-color-danger);
            }
          }
        }

        .card-body {
          padding: 16px;

          .description {
            margin-bottom: 16px;
            color: var(--el-text-color-regular);
            font-size: 14px;
            line-height: 1.5;
          }

          .host-info {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 16px;
            color: var(--el-text-color-secondary);
            font-size: 13px;

            .info-item {
              display: flex;
              align-items: center;
              gap: 4px;

              .el-icon {
                font-size: 14px;
              }

              .host-tags {
                display: inline-flex;
                align-items: center;
                gap: 4px;

                .host-tag {
                  margin: 0;
                }

                .more-hosts {
                  color: var(--el-color-info);
                  font-size: 12px;
                }
              }
            }
          }

          .execution-info {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;

            .info-item {
              display: flex;
              align-items: center;
              gap: 4px;
              color: var(--el-text-color-secondary);
              font-size: 13px;

              .el-icon {
                font-size: 16px;
              }
            }
          }

          .workflow-steps {
            .step-title {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 12px;
              color: var(--el-text-color-secondary);
              font-size: 13px;
              padding: 0;

              .skipped-count {
                margin-left: auto;
                cursor: help;
              }
            }

            :deep(.el-steps) {
              padding: 8px 12px;
              max-height: 200px;
              overflow-y: auto;

              // 自定义滚动条样式
              &::-webkit-scrollbar {
                width: 6px;
              }

              &::-webkit-scrollbar-thumb {
                background: var(--el-border-color-darker);
                border-radius: 3px;
              }

              &::-webkit-scrollbar-track {
                background: var(--el-fill-color-lighter);
                border-radius: 3px;
              }

              .el-step {
                display: flex;
                align-items: center;
                padding: 8px 0;
                margin-right: 12px;

                .el-step__head {
                  margin-right: 8px;
                  flex-shrink: 0;
                }

                .el-step__main {
                  flex: 1;
                  min-width: 0;
                }

                .el-step__title {
                  font-size: 14px;
                  font-weight: 500;
                  line-height: 1.4;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  gap: 8px;

                  .step-name {
                    flex: 1;
                    min-width: 0;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }

                  .step-status {
                    flex-shrink: 0;
                    font-size: 12px;
                    padding: 2px 8px;
                    border-radius: 10px;

                    &.success {
                      background-color: var(--el-color-success-light-9);
                      color: var(--el-color-success);
                    }

                    &.process {
                      background-color: var(--el-color-primary-light-9);
                      color: var(--el-color-primary);
                    }

                    &.error {
                      background-color: var(--el-color-danger-light-9);
                      color: var(--el-color-danger);
                    }

                    &.wait {
                      background-color: var(--el-color-info-light-9);
                      color: var(--el-color-info);
                    }
                  }
                }
              }
            }
          }
        }

        .card-footer {
          padding: 12px 16px;
          border-top: 1px solid var(--el-border-color-lighter);
          display: flex;
          justify-content: space-between;
          align-items: center;
          background-color: var(--el-fill-color-light);

          .time-info {
            display: flex;
            align-items: center;
            gap: 4px;
            color: var(--el-text-color-secondary);
            font-size: 13px;
          }

          .actions {
            display: flex;
            gap: 8px;
          }
        }
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 12px 24px;
      border-top: 1px solid var(--el-border-color-lighter);
      display: flex;
      justify-content: flex-end;
    }
  }
}

.pod-info {
  padding: 8px;
  font-size: 13px;
  min-width: 200px;
  background-color: #2b2b2b;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

  .info-item {
    display: flex;
    margin-bottom: 4px;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #888;
      width: 75px;
      flex-shrink: 0;
      font-weight: 500;
      position: relative;

      &::after {
        content: '：';
        position: absolute;
        right: 0;
      }
    }

    .value {
      flex: 1;
      margin-left: 8px;
      word-break: break-all;
      color: #e6e6e6;
      font-family: var(--el-font-family-monospace);

      &.成功 {
        color: #67c23a;
        font-weight: 500;
      }

      &.运行中 {
        color: #409eff;
        font-weight: 500;
      }

      &.失败 {
        color: #f56c6c;
        font-weight: 500;
      }

      &.pending {
        color: #e6a23c;
        font-weight: 500;
      }
    }
  }
}

.skipped-info {
  padding: 8px;
  min-width: 240px;
  background-color: #2b2b2b;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

  .info-header {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 8px;
    color: var(--el-color-warning);
    font-weight: 500;

    .el-icon {
      font-size: 16px;
    }
  }

  .info-content {
    .skipped-item {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 4px 0;
      color: #e6e6e6;
      font-size: 13px;
      transition: all 0.2s;

      .el-icon {
        color: var(--el-color-warning);
      }

      span {
        font-family: var(--el-font-family-monospace);
        color: #409eff;
        font-weight: 500;
      }

      &:hover {
        background-color: rgba(255, 255, 255, 0.05);
        border-radius: 4px;
        padding: 4px 6px;
        margin: 0 -6px;
      }
    }
  }
}
</style>
